package com.opencee.boot.autoconfigure.web;

import com.opencee.common.security.SecurityProperties;
import com.opencee.common.security.SecurityUser;
import com.opencee.common.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证拦截器
 *
 * @author yadu
 */
public class JWTTokenFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(JWTTokenFilter.class);
    private TokenExtractor tokenExtractor = new BearerTokenExtractor();
    private SecurityProperties properties;

    public JWTTokenFilter(SecurityProperties properties) {
        this.properties = properties;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        try {
            Authentication tokenAuth = this.tokenExtractor.extract(request);
            if (tokenAuth != null) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
                    String token = (String) tokenAuth.getPrincipal();
                    SecurityUser user = JwtUtil.parseJWT(token, properties);
                    if (user != null) {
                        Authentication auth = new UsernamePasswordAuthenticationToken(user, "N/A", user.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(auth);
                    }
                }
            }
        } catch (Exception var10) {
            if (log.isDebugEnabled()) {
                log.debug("Authentication request failed: ", var10.getMessage());
            }
        }

        chain.doFilter(request, response);
    }
}
